package com.cn.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cn.gmall.common.cache.MyRedisSionCache;
import com.cn.gmall.common.constant.RedisConst;
import com.cn.gmall.common.execption.GmallException;

import com.cn.gmall.common.mqconst.MqConst;
import com.cn.gmall.common.result.Result;
import com.cn.gmall.common.result.ResultCodeEnum;
import com.cn.gmall.common.service.RabbitService;
import com.cn.gmall.model.product.*;
import com.cn.gmall.product.mapper.*;
import com.cn.gmall.product.service.ManageService;


import com.google.common.collect.Maps;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
@SuppressWarnings("all")
public class ManageServiceImpl implements ManageService {

    @Autowired
    RabbitService rabbitService;
    @Autowired
    BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    SpuInfoMapper spuInfoMapper;
    @Autowired
    BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    SpuPosterMapper spuPosterMapper;
    @Autowired
    SpuImageMapper spuImageMapper;
    @Autowired
    SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    SkuInfoMapper skuInfoMapper;
    @Autowired
    SkuImageMapper skuImageMapper;


    @Autowired
    SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    RedissonClient redissonClient;

    /**
     * 获取首页分类数据
     *
     * @return
     */
    @Override
    public List<JSONObject> getBaseCategoryList() {

        ArrayList<JSONObject> result = new ArrayList<>();

        List<BaseCategoryView> baseCategoryViewsAll = baseCategoryViewMapper.selectList(null);
//parallelStream()多线程不能保证数据的顺序 线程不安全
//        一级分组
        Map<Long, List<BaseCategoryView>> category1 = baseCategoryViewsAll.stream().
                collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));

        int index = 1;
//       一级分组
        for (Map.Entry<Long, List<BaseCategoryView>> category1Entry : category1.entrySet()) {
//            存放一级分组对象
            JSONObject category1Map = new JSONObject();
            category1Map.put("index", index++);
            category1Map.put("categoryId", category1Entry.getKey());
//            二级分组所有内容
            List<BaseCategoryView> category2All = category1Entry.getValue();
            category1Map.put("categoryName", category2All.get(0).getCategory1Name());
//            遍历二级分组
            //     一级分组下 的所有 二级分组
            ArrayList<JSONObject> category1Child = new ArrayList<>();
            Map<Long, List<BaseCategoryView>> category2 = category2All.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            for (Map.Entry<Long, List<BaseCategoryView>> category2Entry : category2.entrySet()) {

                JSONObject category2Map = new JSONObject();
                category2Map.put("categoryId", category2Entry.getKey());
//                三级分组的全部内容
                List<BaseCategoryView> category3All = category2Entry.getValue();
                category2Map.put("categoryName", category3All.get(0).getCategory2Name());
//           三级分组每个id都不同 直接循环

                ArrayList<JSONObject> category2Child = new ArrayList<>(); //二级分组下 所有三级分组
                category3All.stream().forEach(category3 -> {
                    JSONObject category3Map = new JSONObject();
                    category3Map.put("categoryId", category3.getCategory3Id());
                    category3Map.put("categoryName", category3.getCategory3Name());
//                    将每一个 封装好的三级分组对象 放到category2Child里面
                    category2Child.add(category3Map);
                });

                category2Map.put("categoryChild", category2Child);
//                    将每一个 封装好的二级分组对象 放到category1Child里面
                category1Child.add(category2Map);
            }

            category1Map.put("categoryChild",category1Child);
//                    将每一个 封装好的一级分组对象 放到result里面
                result.add(category1Map);
        }


        return result;
    }

    /**
     * 根据spuId 获取到销售属性值Id 与skuId 组成的数据集
     *
     * @param spuId
     * @return
     */
    @Override
    @MyRedisSionCache(prefix = "skuValue:", suffix = ":info")
    public Map getSkuValueIdsMap(Long spuId) {
        Map<String, String> maps = new HashMap<>();

        List<Map> mapList = skuSaleAttrValueMapper.selectSaleAttrValuesBySpu(spuId);
       /* 别抛异常 否则不走redis
       if (CollectionUtils.isEmpty(mapList)) {
            throw new GmallException("为找到对应数据", 201);
        } else {*/
        for (Map map : mapList) {
            maps.put(map.get("value_ids").toString(), String.valueOf(map.get("sku_id")));
        }


        return maps;
    }

    /**
     * 根据spuId,skuId 获取销售属性数据
     *
     * @param skuId
     * @param spuId
     * @return
     */
    @Override
    @MyRedisSionCache(prefix = "spuSaleAttrList:", suffix = ":info")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
//        三表联查 `spu_sale_attr` `spu_sale_attr_value``sku_sale_attr_value`
        return spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(skuId, spuId);
    }

    /**
     * 根据skuId 获取平台属性数据
     *
     * @param skuId
     * @return
     */
    @Override
    @MyRedisSionCache(prefix = "attrList:", suffix = ":info")
    public List<BaseAttrInfo> getAttrList(Long skuId) {
// `base_attr_info` `sku_attr_value` `base_attr_value` 三表联查
        return baseAttrInfoMapper.selectListAttrInfoBySkuId(skuId);
    }

    /**
     * 根据三级分类id获取分类信息
     *
     * @param category3Id
     * @return
     */
    @Override
    @MyRedisSionCache(prefix = "categoryView:", suffix = ":info")
    public BaseCategoryView getCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    /**
     * 根据skuId 获取最新的商品价格
     *
     * @param skuId
     * @return
     */
    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        RLock lock = redissonClient.getLock(skuId + RedisConst.SKULOCK_SUFFIX);
        //限流 加锁
        lock.lock(RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
        try {
            SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
            if (!ObjectUtils.isEmpty(skuInfo)) {
                return skuInfo.getPrice();
            }
        } finally {
            lock.unlock();
        }
        return new BigDecimal(0);

    }

    /**
     * 根据spuId 获取海报数据
     *
     * @param spuId
     * @return
     */
    @Override
    @MyRedisSionCache(prefix = "spuPoster:", suffix = ":info")
    public List<SpuPoster> findSpuPosterBySpuId(Long spuId) {
        return spuPosterMapper.selectList(new LambdaQueryWrapper<SpuPoster>().eq(SpuPoster::getSpuId, spuId));
    }

    /**
     * 根据skuId获取SkuInfo
     * 查询skuinfo信息和图片列表
     *
     * @param skuId
     * @return
     */
    @Override
    @MyRedisSionCache(prefix = "sku:", suffix = ":info")
    public SkuInfo getSkuInfo(Long skuId) {
        return getSkuInfoDb(skuId);

    }

/*    public static void main(String[] args) {
        String[] strings = new String[]{"11"};
        System.out.println("ArraysUtil.toString(strings) = " + ArraysUtil.toString(strings));
        System.out.println("Arrays.toString(strings) = " + Arrays.toString(strings));
    }*/

    /**
     * 直接从数据库里面查询数据
     *
     * @param skuId
     * @return
     */
    private SkuInfo getSkuInfoDb(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
     /*
     这里不抛异常 如果没有这个对象存在 就在redis里面存一个空对象  防止缓存穿透 和击穿
      if (ObjectUtils.isEmpty(skuInfo)) {
            throw new GmallException("没有输入skuId对应的 skuinfo对象 ",
                    ResultCodeEnum.FAIL.getCode());
        } else {*/
        List<SkuImage> skuImages = skuImageMapper.selectList(new LambdaQueryWrapper<SkuImage>().eq(SkuImage::getSkuId, skuId));
        if (!CollectionUtils.isEmpty(skuImages)) {

            skuInfo.setSkuImageList(skuImages);
        }
        return skuInfo;

    }

    /**
     * 商品下架
     *
     * @param skuId
     */
    @Override
    public void cancelLineSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);//1: 上线 0: 下线
        skuInfoMapper.updateById(skuInfo);
        //        发送消息到mq
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER,
                skuId);
    }

    /**
     * 商品上架
     *
     * @param skuId
     */
    @Override
    public void onLineSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);//1: 上线 0: 下线
        skuInfoMapper.updateById(skuInfo);
//        发送消息到mq
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_UPPER,
                skuId);
    }

    /**
     * sku分页 显示
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<SkuInfo> getSkuPage(Page<SkuInfo> pageParam) {
        return skuInfoMapper.selectPage(pageParam, new LambdaQueryWrapper<SkuInfo>().orderByDesc(SkuInfo::getId));

    }

    /**
     * 保存sku
     *
     * @param skuInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class) //设置回滚 当出现任何异常都要回滚
    public void saveSkuInfo(SkuInfo skuInfo) {
//  1.      保存     skuInfo对象
        if (ObjectUtils.isEmpty(skuInfo)) {
            throw new GmallException("Sku对象保存 不能为空", 201);
        }
        skuInfoMapper.insert(skuInfo);

//   2.     保存skuImageList 中 SkuImage对象
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (CollectionUtils.isEmpty(skuImageList)) {
            throw new GmallException("sku保存时  skuImageList属性为空", 201);
        } else {
            skuImageList.forEach(skuImage -> {
//                只要上面的skuinfo保存后 会 将保存的对象 回传 此时 调skuinfo id已经存在了
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }

//   3.     保存skuAttrValueList 中 SkuAttrValue对象
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (CollectionUtils.isEmpty(skuAttrValueList)) {
            throw new GmallException("sku保存时  skuAttrValueList属性为空", 201);
        } else {
            skuAttrValueList.forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }

//   4     保存 skuSaleAttrValueList 中SkuSaleAttrValue 对象
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();

        if (CollectionUtils.isEmpty(skuSaleAttrValueList)) {
            throw new GmallException("sku保存时  skuSaleAttrValueList属性为空", 201);
        } else {
            skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }
//        给布隆过滤器 加入id
     /*   RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER);
        bloomFilter.add(skuInfo.getId());*/

//        redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER).add(skuInfo.getId());

    }

    /**
     * 根据spuId 查询销售属性集合
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {

        return spuSaleAttrMapper.selectSpuAttrList(spuId);
    }

    /**
     * 根据spuId 获取spuImage 集合
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
       /* LambdaQueryWrapper<SpuImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuImage::getSpuId,spuId);
        return spuImageMapper.selectList(queryWrapper);*/

        return spuImageMapper.selectList(new LambdaQueryWrapper<SpuImage>().eq(SpuImage::getSpuId, spuId));
    }

    /**
     * 保存spu
     *
     * @param spuInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
//      1.  spuInfo 表 保存 spuName  description category3Id tmId 保存表后会 返回对象的id
        if (ObjectUtils.isEmpty(spuInfo)) {
            throw new GmallException("spu对象为空", 2001);
        }
        spuInfoMapper.insert(spuInfo);// 至此以后 spu的id已经回传到spuInfo对象了


//    2.1    spuSaleAttrList 中SpuSaleAttr对象 保存
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (CollectionUtils.isEmpty(spuSaleAttrList)) {
            throw new GmallException("spuSaleAttrList 中未有数据", 2001);
        }
        spuSaleAttrList.stream().forEach(spuSaleAttr -> {
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            /**
             * SpuId 从spuInfo表里面
             */
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);

            //        2.2  spuSaleAttrValueList SpuSaleAttrValue保存
            if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                spuSaleAttrValueList.stream().forEach(spuSaleAttrValue -> {
                    /**
                     * SpuId 从spuInfo表里面
                     * SaleAttrName 从spuSaleAttr 里面来
                     */
                    spuSaleAttrValue.setSpuId(spuInfo.getId());
                    spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                    spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                });

            } else {
                throw new GmallException("spuSaleAttrList---> spuSaleAttrValueList为空 ", 2001);
            }
        });


//       3. spuImageList 中 SpuImage对象保存
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (CollectionUtils.isEmpty(spuImageList)) {
            throw new GmallException("spuImageList 中没有任何照片", 2001);
        }
        spuImageList.stream().forEach(spuImage -> {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
//      4.  spuPosterList 中的 SpuPoster对象保存
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (CollectionUtils.isEmpty(spuPosterList)) {
            throw new GmallException("spuPosterList 中数据为空", 2001);
        }
        spuPosterList.stream().forEach(spuPoster -> {
            spuPoster.setSpuId(spuInfo.getId());
            spuPosterMapper.insert(spuPoster);
        });

    }

    /**
     * 获取销售属性数据
     *
     * @return
     */
    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {

        return baseSaleAttrMapper.selectList(null);
    }

    /**
     * spu分页列表
     *
     * @param spuInfoPage
     * @param spuInfo
     * @return
     */
    @Override
    public IPage<SpuInfo> selectSpuPage(Page<SpuInfo> spuInfoPage, SpuInfo spuInfo) {

        LambdaQueryWrapper<SpuInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuInfo::getCategory3Id, spuInfo.getCategory3Id());
        queryWrapper.orderByAsc(SpuInfo::getId);
        return spuInfoMapper.selectPage(spuInfoPage, queryWrapper);
    }

    /**
     * 根据平台属性Id 获取到平台属性值集合
     * (先去 base_attr_info表中找到 对应 attrId的相关数据)
     * 再
     *
     * @param attrId
     * @return
     */
    @Override
    public BaseAttrInfo getAttrInfoById(Long attrId) {
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        List<BaseAttrValue> attrValueList = getAttrValueList(attrId);
        if (baseAttrInfo != null) {
            baseAttrInfo.setAttrValueList(attrValueList);
        }
        return baseAttrInfo;
    }

    /**
     * 根据平台属性Id 获取到平台属性值集合
     *
     * @param attrId
     * @return
     */
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseAttrValue::getAttrId, attrId);
        queryWrapper.orderByAsc(BaseAttrValue::getId);
        return baseAttrValueMapper.selectList(queryWrapper);
    }

    /**
     * 保存修改
     *
     * @param baseAttrInfo
     */
    @Override
    //事物默认回滚 范围 runtimeException
    @Transactional(rollbackFor = Exception.class)

    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        if (baseAttrInfo.getId() == null) {
            //新增 保存 平台属性
            baseAttrInfoMapper.insert(baseAttrInfo);
        } else {
//            修改 有id
            baseAttrInfoMapper.updateById(baseAttrInfo);
//            根据attr_id查
            LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BaseAttrValue::getAttrId, baseAttrInfo.getId());
            baseAttrValueMapper.delete(queryWrapper);
        }
        /**
         *
         */
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (!CollectionUtils.isEmpty(attrValueList)) {

            attrValueList.stream().forEach(baseAttrValue -> {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            });
        }
    }

    /**
     * 根据分类Id 获取平台属性集合
     *
     * @param category1Id
     * @param category2Id
     * @param category3Id
     * @return
     */
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {

        return baseAttrInfoMapper.selectListAttrInfo(category1Id, category2Id, category3Id);
    }

    /**
     * 获取三级分类数据
     *
     * @param category2Id
     * @return
     */
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        LambdaQueryWrapper<BaseCategory3> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseCategory3::getCategory2Id, category2Id);
        return baseCategory3Mapper.selectList(queryWrapper);

    }

    /**
     * 获取二级列表
     *
     * @param category1Id
     * @return
     */
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        LambdaQueryWrapper<BaseCategory2> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseCategory2::getCategory1Id, category1Id);
        return baseCategory2Mapper.selectList(queryWrapper);

    }

    /**
     * 获取一级列表
     *
     * @return
     */
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);

    }
}
